import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:media_kit/media_kit.dart';
import 'app/routes/app_pages.dart';
import 'app/services/theme_service.dart';
import 'app/services/locale_service.dart';
import 'app/services/token_service.dart';
import 'app/services/user_service.dart';
import 'app/routes/app_routes.dart';
import 'app/services/translation_service.dart';
import 'app/service_initializer.dart';
import 'app/utils/themes/app_theme.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/foundation.dart';

void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();

  PaintingBinding.instance.imageCache.maximumSize = 100;
  // 性能优化配置
  // 设置图像缓存最大大小（默认为1000，减少内存占用）
  // 设置图像缓存最大字节数（默认为100MB，减少内存占用）
  PaintingBinding.instance.imageCache.maximumSizeBytes = 50 * 1024 * 1024; // 50MB
  
  // 在发布模式下禁用检查模式，提高性能
  if (!kDebugMode) {
    debugPrintRebuildDirtyWidgets = false;
    debugPrintLayouts = false;
    debugPrint = (String? message, {int? wrapWidth}) {};
  }
  
  // 初始化MediaKit
  try {
    MediaKit.ensureInitialized();
    debugPrint('MediaKit初始化成功');
  } catch (e) {
    debugPrint('MediaKit初始化失败: $e');
    // 继续执行，应用其他功能不依赖MediaKit仍可使用
  }
  
  // 初始化所有服务
  try {
    await ServiceInitializer.init();
    debugPrint('服务初始化完成');
  } catch (e) {
    debugPrint('服务初始化过程中出现错误: $e');
    // 尝试继续执行应用
  }
  
  // 获取已初始化的服务实例
  final localeService = Get.find<LocaleService>();
  final themeService = Get.find<ThemeService>();
  final tokenService = Get.find<TokenService>();
  
  // 如果有登录凭证，则尝试自动加载用户信息
  if (tokenService.isLoggedIn()) {
    try {
      // 加载用户信息
      await Get.find<UserService>().getUserInfo();
    } catch (e) {
      // 如果加载失败，清除登录凭证
      debugPrint('自动恢复用户登录失败: $e');
      tokenService.clearToken();
    }
  }
  
  runApp(
    GetMaterialApp(
      title: '海隆智联',
      // 启用GetX日志
      enableLog: true,
      initialRoute: tokenService.isLoggedIn() ? Routes.home : Routes.login,
      getPages: AppPages.routes,
      
      // 使用自定义主题配置
      theme: AppTheme.light,
      darkTheme: AppTheme.dark,
      themeMode: themeService.theme,
      
      // 国际化配置
      locale: localeService.locale,
      fallbackLocale: const Locale('zh', 'CN'),
      translations: TranslationService(),
      
      debugShowCheckedModeBanner: false,
      builder: EasyLoading.init(),
    ),
  );
}
